package com.blue.alipay.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.demo.trade.utils.ZxingUtils;
import com.blue.alipay.contants.WeXinConfig;
import com.blue.alipay.utils.controller.BaseController;
import com.blue.alipay.utils.date.DateUtil;
import com.blue.alipay.utils.http.HttpClientsUtil;
import com.blue.alipay.utils.http.XMLUtil;
import com.blue.alipay.utils.sign.WxSignature;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @描述 微信h5
 * @时间 2017-9-26 20:48
 * @作者 肖亦鸣
 */
@Controller
@RequestMapping("wx_wappay")
public class WeXinWapApyController extends BaseController {
    private static Logger logger = LogManager.getLogger(WeXinWapApyController.class.getName());

    private final String PATH = "wx_wappay/";

    @RequestMapping("index.html")
    public String index() throws Exception {
        logger.info("index...");
        return PATH + "index";
    }

    @RequestMapping("pay.html")
    public String pay() throws Exception {
        logger.info("pay...");
        return PATH + "pay";
    }

    @RequestMapping("dopay.html")
    public String doPay() throws Exception {
        logger.info("doPay...");
        SortedMap<String, String> paramMap = buildParamMap();
        // 交易类型  H5支付的交易类型为MWEB
        paramMap.put("trade_type", "MWEB");
        String resXml = execute(WeXinConfig.API_UNIFIEDORDER, paramMap, WeXinConfig.parterKey);
        // 解析返回结果
        Map<String, String> resMap = XMLUtil.XMLToMap(resXml);
        logger.info("resMap:{}", JSON.toJSONString(resMap));
        String url = "https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=" + resMap.get("prepay_id") + "&redirect_url=" + WeXinConfig.return_url;
        logger.info("url:{}", url);
        response.sendRedirect(url);
        return PATH + "pay";
    }


    @RequestMapping(value = "notify_url.html", method = RequestMethod.POST)
    @ResponseBody
    public String notifyUrl() throws Exception {
        logger.info("notify_url...");
        Map requestParams = request.getParameterMap();
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
        logger.info("notify_url...url:{}", basePath + request.getQueryString());
        logger.info("notify_url...requestParams:{}", JSON.toJSONString(requestParams));
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        //sb为微信返回的xml
        logger.info("sb:{}", sb);
        Map<String, String> resMap = XMLUtil.XMLToMap(sb.toString());
        logger.info("resMap:{}", JSON.toJSONString(resMap));

        //这块有问题~
        boolean verify = WxSignature.verify(resMap, WeXinConfig.parterKey);
        logger.info("verify:{}", verify);

        //验签,返回给微信
        if (verify) {

        }
        //商户处理后同步返回给微信参数
        SortedMap<String, String> returnMap = new TreeMap<>();
        returnMap.put("return_code", "SUCCESS");
        returnMap.put("return_msg", "OK");

        return XMLUtil.mapToXML(returnMap);
    }

    @RequestMapping(value = "return_url.html")
    public String returnUrl() throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        logger.info("returnUrl requestParams:{}", JSON.toJSONString(request.getParameterMap()));
        request.setAttribute("msg", "success");
        request.setAttribute("returnMsg", JSON.toJSONString(requestParams));
        return PATH + "return_url";
    }

    public String execute(String url, SortedMap<String, String> paramMap, String parterKey) {
        // 生成签名
        String sign = WxSignature.generate(paramMap, parterKey);
        paramMap.put("sign", sign);
        logger.info("request wechat api " + url + " params: {}", JSON.toJSONString(paramMap));
        // 将请求参数转换为xml格式
        String reqXml = XMLUtil.mapToXML(paramMap);
        String resp;
        long start = System.currentTimeMillis();
        // 发送请求
        // 不需要证书
        if (sslcsf == null) {
            resp = HttpClientsUtil.httpClientPost(url, reqXml);
        }
        // 需要证书
        else {
            resp = HttpClientsUtil.httpClientSLLPost(sslcsf, url, reqXml);
        }
        long end = System.currentTimeMillis();
        logger.info("request wechat api " + url + " cost " + (end - start) + " ms. response: {}", resp);
        return resp;
    }

    private SSLConnectionSocketFactory sslcsf;

    public void setSSLConnectionSocketFactory(SSLConnectionSocketFactory sslcsf) {
        this.sslcsf = sslcsf;
    }

    private static SortedMap<String, String> buildParamMap() {
        SortedMap<String, String> paramMap = new TreeMap<String, String>();
        // 应用id
        paramMap.put("appid", WeXinConfig.appId);
        // 商户号
        paramMap.put("mch_id", WeXinConfig.mchId);
        // 随机字符串
        paramMap.put("nonce_str", "kee0v91lnlijk8jym1jsywz2dwls3mkg");
        // 商品标题
        paramMap.put("body", "body_测试商品0.01元");
        paramMap.put("detail", "detail_测试商品0.01元");
        // 商户订单号
        paramMap.put("out_trade_no", "" + new Random().nextInt(999999999) + new Random().nextInt(999999999));
        // 总金额(单位分)
        paramMap.put("total_fee", "1");
        // 终端IP
        paramMap.put("spbill_create_ip", "10.253.8.233");
        // 下面设置交易过期时间：如果不传则设为半小时
        Date currentDate = new Date();
        // 交易起始时间
        paramMap.put("time_start", DateUtil.formatDate(currentDate, DateUtil.YYYYMMDDHHmmss));
        // 交易结束时间
        Calendar calender = Calendar.getInstance();
        calender.setTime(currentDate);
        calender.add(Calendar.MINUTE, 30);
        paramMap.put("time_expire", DateUtil.formatDate(calender.getTime(), DateUtil.YYYYMMDDHHmmss));
        // 自定义支付参数
        String customPayParam = "orderId=132468798798";
        // 异步通知接口
        String notifyUrl = WeXinConfig.notify_url + "?" + customPayParam;
        paramMap.put("notify_url", notifyUrl);
        // 用户的openid (公众号支付必传)
        //    paramMap.put("openid", WeXinConfig.openId);
        //用户标识
//        paramMap.put("openid", WeXinConfig.openId);
        // 二维码中包含的商品ID (扫码支付必传)
        paramMap.put("product_id", "79874621564812145");

        return paramMap;
    }
}
